package com.fastjrun.security.authentication.wechat;

import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于校验用户opnid是否允许通过认证
 */
public class WechatAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    public WechatAuthenticationFilter() {
        super(new AntPathRequestMatcher("/wechat/callback", HttpMethod.GET.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        // 先获取seesion中的openId
        String openId =
                (String) request.getSession().getAttribute(WechatConstants.SESSION_KEY_OPNEID);
        request.getSession().removeAttribute(WechatConstants.SESSION_KEY_OPNEID);
        WechatAuthenticationToken authRequest = new WechatAuthenticationToken(openId);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 将 sessionID和hostname添加 到MobileAuthenticationToken
     */
    protected void setDetails(HttpServletRequest request,
                              WechatAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
